from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

# Create your views here.
from rest_framework import status, mixins
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_simplejwt.views import TokenViewBase

from users.models import User
from users.serializers import (
    CreateUserSerializer,
    MyTokenSerializer,
    UserDetailSerializer,
    EmailSerializer,
    UserAddressSerializer,
    AddressTitleSerializer,
)


class UserCountView(APIView):
    """校验用户名是否已注册"""

    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        data = {"username": username, "count": count}
        return Response(data)


class MobileCountView(APIView):
    """校验电话号码是否注册"""

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {"mobile": mobile, "count": count}
        return Response(data)


class UserRegisterView(CreateAPIView):
    """
    用户注册
    传入参数：
        username, password, password2, sms_code, mobile, allow
    """

    serializer_class = CreateUserSerializer


class LoginView(TokenViewBase):
    serializer_class = MyTokenSerializer  # 使用刚刚编写的序列化类

    # post方法对应post请求，登陆时post请求在这里处理
    def post(self, request, *args, **kwargs):
        # 使用刚刚编写时序列化处理登陆验证及数据响应
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        return Response(serializer.validated_data, status=status.HTTP_200_OK)


class UsernameMobileAuthBackend(ModelBackend):
    """用户名或手机登录"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """判断用户名(手机号码)和密码是否正确"""
        query_set = User.objects.filter(Q(username=username) | Q(mobile=username))
        try:
            if query_set.exists():
                user = query_set.get()
                if user.check_password(password):
                    return user
        except:
            return None
        return None


class UserDetailView(RetrieveAPIView):
    """用户详情"""

    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]  # 必须要登录后才能访问

    def get_object(self):
        return self.request.user


class EmailVerifyView(UpdateAPIView):
    """
    保存用户邮箱
    """

    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):
        return self.request.user


# class VerifyEmailView(APIView):
#     """验证邮箱"""
#
#     def get(self, request):
#         token = request.query_params.get("token")
#         if not token:
#             return Response({"message": "缺少token"}, status=status.HTTP_400_BAD_REQUEST)
#         user = User.check_verify_email_token(token)  # 检测token是否有效
#         if user is None:
#             return Response({"message": "链接信息无效"}, status=status.HTTP_400_BAD_REQUEST)
#         else:
#             user.email_active = True
#             user.save()
#             return Response({"message": "OK"})


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """用户地址增删"""

    serializer_class = UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        """过滤未删除的数据"""
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response(
            {
                "user_id": user.id,
                "default_address_id": user.default_address_id,
                "limit": 20,
                "addresses": serializer.data,
            }
        )

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count > 20:
            return Response(
                {"message": "保存地址数据已达到上限,最多只能保留20条地址数据"},
                status=status.HTTP_400_BAD_REQUEST,
            )
        return super().create(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()
        # 进行逻辑删除
        address.is_deleted = True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=["put"], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({"message": "OK"}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=["put"], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)
